package com.css.landslide.risk.service.impl;


import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.css.config.ThreadPoolConfig;
import com.css.datasourceSwitch.entity.ProvinceDS;
import com.css.landslide.risk.entity.LandslideRiskLevel;
import com.css.landslide.risk.mapper.LandslideRiskLevelMapper;
import com.css.landslide.risk.param.LandslideParam;
import com.css.landslide.risk.service.LandslideRiskLevelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author dingling
 * @desc 滑坡危险性
 * @date 2024-09-26 16:19
 **/

@Slf4j
@Service
public class LandslideRiskLevelServiceImpl extends ServiceImpl<LandslideRiskLevelMapper, LandslideRiskLevel> implements LandslideRiskLevelService {



    @Override
    public List<LandslideRiskLevel> selectRiskLandslideProvince(LandslideParam dsEntity){
        try {
            DynamicDataSourceContextHolder.push(dsEntity.getDataSourceKey());
            QueryWrapper<LandslideRiskLevel> wrapper = new QueryWrapper<>();
            wrapper.eq("earth_quake_id",dsEntity.getEarthQuakeId());
            if (StringUtils.isNotBlank(dsEntity.getInfluenceVersion())){
                wrapper.eq("dz_version",dsEntity.getInfluenceVersion());
            }
            return  this.getBaseMapper().selectList(wrapper);
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            DynamicDataSourceContextHolder.clear();
        }

    }


    @Override
    public int deleteProvince(LandslideParam riskLevel) {
        try {
            DynamicDataSourceContextHolder.push(riskLevel.getDataSourceKey());
            QueryWrapper<LandslideRiskLevel> rmWrapper = new QueryWrapper<>();
            rmWrapper.eq("earth_quake_id",riskLevel.getEarthQuakeId());
            rmWrapper.eq("dz_version",riskLevel.getInfluenceVersion());
            return this.baseMapper.delete(rmWrapper);
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            DynamicDataSourceContextHolder.clear();
        }
    }



    @Override
    public Integer batchInsert(LandslideParam dsEntity, List<LandslideRiskLevel> levels) {
        try {

//            levels.forEach(level -> {
//                this.getBaseMapper().insert(level);
//            });
//            return 1;

            int batch = 2000;

            int b = (int) Math.ceil(levels.size() *1.0 / batch );

            List<CompletableFuture<?>> futures = new ArrayList<>();

            for (int i = 0; i < b; i++) {

                int finalI = i;
                CompletableFuture<?> future = CompletableFuture.runAsync(() -> {

                    try {
                        DynamicDataSourceContextHolder.push(dsEntity.getDataSourceKey());
                        List<LandslideRiskLevel> riskLevels = levels.subList(finalI * batch, Math.min((finalI + 1) * batch, levels.size() - 1));
                        this.baseMapper.batchInsertLandslideRiskLevel(riskLevels);

                    }catch (Exception e){
                        log.error(e.getMessage());
                        throw new RuntimeException(e);
                    }finally {
                        DynamicDataSourceContextHolder.clear();
                    }

                }, ThreadPoolConfig.exeBizThreadPoolExecutor);

                futures.add(future);

            }
            CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
            allFutures.get();

            return 1;
        }catch (Exception e){
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }


}
